package org.qy.star_server.controller;

import lombok.extern.slf4j.Slf4j;
import org.qy.star_server.core.Binding;
import org.qy.star_server.core.BrokerServer;
import org.qy.star_server.core.User;
import org.qy.star_server.core.VirtualHost;
import org.qy.star_server.data.center.DiskDataCenter;
import org.qy.star_server.data.center.MemoryDataCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yinger
 * @description TODO
 * @date 2024/3/31 16:05
 **/
@Slf4j
@RestController
@RequestMapping("/binding")
public class BindingController {
    private final MemoryDataCenter memory = BrokerServer.memory;

    @RequestMapping("/add")
    public boolean addBinding(Binding binding) {
        try {
            User user =  memory.selectUser(binding.getUsername());
            if (user == null) {
                return false;
            }
            return user.queueBind(binding.getVirtualHostName(), binding.getExchangeName(), binding.getQueueName(), binding.getBindingKey()).isEmpty();
        } catch (Exception e) {
            log.error("添加绑定失败", e);
            return false;
        }
    }

    @RequestMapping("/v-hostAll")
    public List<Binding> getBindings(String virtualHostName, String username) {
        System.out.println(virtualHostName + "用户：" + username);
        try {
            if ("All".equals(virtualHostName)) {
                List<Binding> bindings = new ArrayList<>();
                List<VirtualHost> virtualHosts =  memory.selectVirtualHostByUser(username);
                for (VirtualHost virtualHost : virtualHosts) {
                    bindings.addAll( memory.selectBindingByVirtualHost(username, virtualHost.getVirtualHostName()));
                }
                System.out.println("获取到绑定数量：" + bindings.size());
                System.out.println(bindings);
                return bindings;
            } else {
                List<Binding> bindings =  memory.selectBindingByVirtualHost(username, virtualHostName);
                System.out.println("获取到绑定数量：" + bindings.size());
                System.out.println(bindings);
                return bindings;
            }
        } catch (Exception e) {
            log.error("获取绑定失败", e);
            return null;
        }
    }

}
